package TCPSocket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author 王艺锡
 * @version 1.0
 */
    //使用字符流
public class SocketTCP03Client {
    public static void main(String[] args)  throws IOException {
        //1.连接服务端(ip,端口)
        //连接本机的9999端口，如果连接成功，则返回一个Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //2.连接上后，通过 socket.getOutputStream()得到和 Socket对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //转换为字符流
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        //3.通过输出流，写入数据到数据通道,使用字符流


        bw.write("hello,server");
        bw.newLine();
        bw.flush();
        socket.shutdownOutput();

        //4.获取
        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = " ";
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }

        //4.关闭对应的流和socket(必须)
        bw.close();
        br.close();
        socket.close();
    }
}
